
//  AppDelegate.swift
//  DSWeibo
//
//  Created by J on 16/2/21.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit

let XMGSwitchRootViewControllerKey  = "XMGSwitchRootViewControllerKey"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        //注册一个通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.XMGSwitchRootViewController), name: XMGSwitchRootViewControllerKey, object: nil)
        
        //设置导航条和工具条的外观
        //因为外观一旦设置全局有效,所以应该在程序一进来就设置
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()

        
        //1.window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        //2.root控制器
        window?.rootViewController = defaultController()//MainViewController的view还没有显示
        
        window?.makeKeyAndVisible()//要显示view就要调用懒加载
        return true

    }
    
     func XMGSwitchRootViewController(noti:NSNotification){
        
        print(noti.object)
        if noti.object as! Bool {
            window?.rootViewController = MainViewController()
        }else{
            window?.rootViewController = WelcomeViewController()
        }
        
    }
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func defaultController() -> UIViewController{
        if UserAccount.userLogin() {
            return isNewUpdate() ? NewFeatureCollectionViewController() : WelcomeViewController()
        }
        
        return MainViewController()
    }
    private let key  = "CFBundleShortVersionString"

    private func isNewUpdate ()-> Bool{
        let currentVersion = NSBundle.mainBundle().infoDictionary![key] as!String
        let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey(key) as?String ?? ""
                if  currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending {
                    
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: key)
            return true
        }
        
        return false
        
        
        
        
        
    }

}

